package com.qgs.rabbitmqapi.consumer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/23 13:58
 * @Version 1.0
 */
public class MyConsumer extends DefaultConsumer {

    Logger logger = LoggerFactory.getLogger(com.qgs.rabbitmqapi.consumer.MyConsumer.class);

    private Channel channel;

    public MyConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        super.handleDelivery(consumerTag, envelope, properties, body);
        logger.info("-------------consumer message-----------------");
        logger.info("consumerTag:"+consumerTag);
        logger.info("envelope:"+envelope);
        logger.info("properties:"+properties); //consumerTag是设备标签。
        logger.info("客户端接收到的message是:"+new String(body,"UTF-8"));

        /*14:07:43.916 [pool-1-thread-4] INFO com.qgs.rabbitmqapi.consumer.MyConsumer - -------------consumer message----------------- 14:07:43.916 [pool-1-thread-4] INFO com.qgs.rabbitmqapi.consumer.MyConsumer - consumerTag:amq.ctag-HhmfV16bmJvmVv7srAUVMQ
        14:07:43.916 [pool-1-thread-4] INFO com.qgs.rabbitmqapi.consumer.MyConsumer - envelope:Envelope(deliveryTag=5, redeliver=false, exchange=test_consumer_exchange, routingKey=consumer.save)
        14:07:43.916 [pool-1-thread-4] INFO com.qgs.rabbitmqapi.consumer.MyConsumer - properties:#contentHeader<basic>(content-type=null, content-encoding=null, headers=null, delivery-mode=null, priority=null, correlation-id=null, reply-to=null, expiration=null, message-id=null, timestamp=null, type=null, user-id=null, app-id=null, cluster-id=null)
        14:07:43.916 [pool-1-thread-4] INFO com.qgs.rabbitmqapi.consumer.MyConsumer - 客户端接收到的message是:hello rabbitmq Consumer message
        */

        //签收消息（任务队列的关键。）
        channel.basicAck(envelope.getDeliveryTag(),false);
        //false 表示不支持批量签收，即消费一个签收一个。
        //envelope.getDeliveryTag() 是获取这条消息的标签。
    }
}
